#!/usr/bin/perl
#
# Make a data file for place info
# This is a structured variable containing lots of country info.
# Maybe useless.
# Sub-id structure:
#    $country{$sub} contains an array of "same shape" things
#
use Data::Dumper;
use FileTable;
use POSIX;

open(DATA, "tools/tabulate db/places name type within longname maintainer users userlist|");

while (<DATA>) {
    next if /^#/;
    ($key, $name, $type, $within, $longname, $maintainer, $users, $userlist) = split("\t");
    $place{$key}{name} = $name;
    $usercount = split(" ", $userlist);
    $place{$key}{oldusers} = $users;
    $place{$key}{usershere} = $usercount;
    $place{$key}{users} = 0; # if the sumcounts() doesn't increase it, it is zero
    next if (!$within); # don't bother if top node
    $place{$key}{up} = $within;
    $place{$within}{down} = [] if !$place{$within}{down};
    push(@{$place{$within}{down}}, $key);
}
# do a prefix traversal to sum the usercounts
print STDERR "Computing usercounts\n";
sumcounts(1);
# and then go back....
$file = FileTable::open("db/places", O_RDWR);
for $key (keys(%place)) {
    if ($place{$key}{down} || $place{$key}{users} != $place{$key}{oldusers}) {
	$rec = $file->get($key);
	if (!$rec) {
	    print STDERR "Error: $key not found\n";
	    next;
	}
	$subs = join(" ", sort {$a <=> $b} @{$place{$key}{down}});
	if ($subs ne $rec->{contains} ||
	    $rec->{users} ne $place{$key}{users}) {
	    print STDERR "W(", $rec->{name}, "):$rec{users}\n"
		if -t STDERR;
	    $rec->{contains} = $subs;
	    $rec->{users} = $place{$key}{users};
	    $rec->store('NOTEXT');
	}
    }
}

sub sumcounts {
    my $recno = shift;
    my $level = shift;
    my $users = $place{$recno}{usershere};
    if ($place{$recno}{down}) {
	for $sub (@{$place{$recno}{down}}) {
	    if ($level > 10) {
		die "Error: $recno is part of a hierarchy loop\n";
	    }
	    $users += sumcounts($sub, $level + 1);
	}
    }
    $place{$recno}{users} = $users;
    return $users;
}

	







